<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="占用状态" prop="status">
        <el-select v-model="queryParams.status">
          <el-option label="空闲" :value="0"></el-option>
          <el-option label="在用" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          :disabled="queryParams.locationId == null"
          @click="openForm('create', queryParams.locationId)"
          v-hasPermi="['call:location:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增号码
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <el-row :gutter="20" class="h-[calc(100vh-320px)]">
    <el-col :span="6" class="h-full">
      <el-card class="h-full" body-style="height: 92%" shadow="never" style="border: none">
        <el-scrollbar class="">
          <el-tree
            :props="{ label: 'name' }"
            :data="areaList"
            node-key="id"
            ref="selectTree"
            @current-change="handleCheckChange"
            :expand-on-click-node="false"
          >
            <template #default="{ node, data }">
              <div>
                <span>{{ node.label }}</span>
                <span>
                  <a v-if="countMap"> ({{ countMap[data.id] ? countMap[data.id] : 0 }}) </a>
                </span>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </el-card>
    </el-col>
    <el-col :span="18">
      <el-card class="h-full" body-style="height: 94%;" shadow="never" style="border: none">
        <div class="mb-20px text-14px">
          <span v-if="queryParams.locationId">该归属地下</span>
          <span v-else>表格内</span>
          <span>"vos点呼群呼主叫"号码数量</span>
          <span class="color-#0052cc px-3px">{{ vosNumberCount }}</span
          >个,
          <span>"双向回拨telX"号码数量</span>
          <span class="color-#0052cc px-3px">{{ recallNumberCount }}</span
          >个;
          <span>"占用"的号码数数量</span>
          <span class="color-#0052cc px-3px">{{ usedNumberCount }}</span
          >个,
          <span>"空闲"的号码数量</span>
          <span class="color-#0052cc px-3px">{{ idleNumberCount }}</span
          >个
        </div>

        <el-table
          border
          :header-cell-style="{ background: '#f0f0f0' }"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
        >
          <el-table-column label="归属地" align="center" prop="locationName" />
          <el-table-column label="号码" align="center" prop="number" />
          <el-table-column label="号码类型" align="center" prop="type">
            <template #default="scope">
              <div>
                <el-tag v-if="scope.row.type == 1">vos点呼群呼主叫号码</el-tag>
                <el-tag v-if="scope.row.type == 2" type="success">双向回拨telX</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="占用状态" align="center" prop="status">
            <template #default="scope">
              <div>
                <el-tag v-if="scope.row.status">在用</el-tag>
                <el-tag v-else type="info">空闲</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="在用的企业" align="center" prop="tenantName" />

          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
          />
          <el-table-column label="操作" align="center" width="140px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', queryParams.locationId, scope.row.id)"
                v-hasPermi="['call:location:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['call:location:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <NumberForm ref="formRef" @success="getSuccess" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as LocationApi from '@/api/call/location'
import * as AreaApi from '@/api/system/area'
import * as VosNumberApi from '@/api/call/vosnumber'
import NumberForm from './NumberForm.vue'
defineOptions({ name: 'NumberPool' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const simpleList = ref([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vosNumberCount = ref(0)
const recallNumberCount = ref(0)
const usedNumberCount = ref(0)
const idleNumberCount = ref(0)
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await VosNumberApi.getVosNumberPage(queryParams)
    list.value = data.result.list
    total.value = data.result.total
    vosNumberCount.value = data.vosNumberCount
    recallNumberCount.value = data.recallNumberCount
    usedNumberCount.value = data.usedNumberCount
    idleNumberCount.value = data.idleNumberCount
  } finally {
    loading.value = false
  }
}

// 地区表格的数据
const areaList = ref([])
/**
 * 获得数据列表
 */
const getAreaList = async () => {
  const data = await AreaApi.getAreaTree()
  areaList.value = data.map((i) => {
    i.children = i.children.map((t) => {
      t.children = []
      return t
    })
    return i
  })
}
const selectTree = ref()
const handleCheckChange = (data, checkObj) => {
  if (queryParams.locationId != data.id) {
    queryParams.locationId = data.id
    getList()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.locationId = undefined
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, locationId: number, id?: number) => {
  formRef.value.open(type, locationId, id)
}

const { push } = useRouter()
const editNumber = (id) => {
  push({ path: '/number-pool/number/' + id })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await VosNumberApi.deleteVosNumber(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const countMap = ref()
const getCountMap = async () => {
  countMap.value = await VosNumberApi.getVosNumberCount()
}

const getSuccess = async () => {
  await getList()
  await getAreaList()
  await getCountMap()
}
/** 初始化 **/
onMounted(async () => {
  await getList()
  await getAreaList()
  await getCountMap()
})
</script>
